/* 
 * 提升交互性
 * @Author:Mr.Alex
 * @Email:<mr.wang@wangqiqiang.com>
 * @version:1.0.5
 * @date:2017-11-23 09:45:00
 * @desc:
 *		1.支持移动端;
 *		2.支持动态绑定
 */
$(function(){
	
	$(document).ajaxStart(function(){
		Pace.restart();
	});
	
	$(document).keyup(function(event){
		if( event.keyCode === 27 )
		{
			parent.layer.close(parent.layer.getFrameIndex(window.name));
		}
	});
	
	$("[rel-action=form]").submit(function(){
		return form_submit(this);
	});
	
	$(document).on("click","[rel-action=dialog]",function(){
		var title = $(this).attr("title") || $(this).attr('rel-title');
		var shade = $(this).attr("rel-shade") || 0.8;
		var width = $(this).attr("rel-width") || 768;
		var height = $(this).attr("rel-height") || 480;
		var url = $(this).attr("href") || $(this).attr('rel-url');
			width = window.screen.availWidth > width ? width : window.screen.availWidth - 20;
			height = window.screen.availHeight > height ? height : window.screen.availHeight - 20;
		layer.open({
			type: 2,
			title: title,
			shade: shade,
			shadeClose: true,
			//closeBtn: false,
			area: [width + 'px',height + 'px'],
			content: url
		});
		
		return false;
	});
	
	$(document).on("click","[rel-action=dialog-upload]",function(){
		var title = $(this).attr('rel-title') || '文件上传';
		var shade = $(this).attr("rel-shade") || 0;
		var width = $(this).attr("rel-width") || 480;
		var height = $(this).attr("rel-height") || 300;
		var url = $(this).attr('rel-url');
			width = window.screen.availWidth > width ? width : window.screen.availWidth - 20;
			height = window.screen.availHeight > height ? height : window.screen.availHeight - 20;
		layer.open({
			type: 2,
			title: title,
			shade: parseFloat(shade),
			shadeClose: true,
			//closeBtn: false,
			area: [width + 'px',height + 'px'],
			content: url
		});
		
		return false;
	});
	
	$("[rel-action=form-file]").submit(function(){
		var url = $(this).attr("action");
		var method = $(this).attr("method");
		var sign = $('[name=sign]',this).val();

		$(this).ajaxSubmit({
			url:url,
			type:method,
			dataType:"json",
			success:function(data){
				if(data.status == 1)
				{
					layer.msg('上传成功');
					parent.$('[rel-sign='+sign+']').val(data.info.url);
					window.setTimeout(function(){
						parent.layer.close(parent.layer.getFrameIndex(window.name));
					},1000);
				}
				if(data.status == 0)
				{
					layer.msg(data.info,{
					  shift:6
					});
				}
			},
			error:function(XmlHttpRequest,textStatus,errorThrown){}
		});

		return false;
	});
	
	$(document).on("click","[rel-action=delete]",function(){
		var url = $(this).attr("href") || $(this).attr("rel-url");
		var msg = $(this).attr("rel-msg") || "确定删除，删除后不可恢复！";
		
		var btnCertain = $(this).attr("rel-certain") || "删除";
		var btnCancel = $(this).attr("rel-cancel") || "取消";
		
		layer.confirm(msg,{
			btn:[btnCertain,btnCancel]
		},function(){
			$.get(url,function(data){
				layer.msg(data.info);
				if(data.status == 1)
				{
					window.setTimeout(function(){
						document.location.href = data.url;
					},1000);
				}
			});
		});
		
		return false;
	});
	
	/**
	 * 定向选择
	 * demo1
	 *	<div class="input-group">
	 *		<div class="input-group-btn">
	 *			<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
	 *				<span class="placeholder">请选择</span>
	 *				<span class="fa fa-caret-down"></span>
	 *			</button>
	 *			<ul class="dropdown-menu" rel-action="target" rel-target="[name=number]">
	 *				<li><a href="javascript:void(0);" rel-data="require" rel-placeholder="已填写">必填</a></li>
	 *				<li><a href="javascript:void(0);" rel-data="read" rel-readonly="true">只读</a></li>
	 *				<li><a href="javascript:void(0);" rel-data="reset" rel-reset="true">重置</a></li>
	 *				<li><a href="javascript:void(0);" rel-data="data">普通</a></li>
	 *				<li><a href="javascript:void(0);" rel-data="last" rel-target="[name=other]" rel-reset="true">例外</a></li>
	 *				<li class="divider"></li>
	 *				<li><a href="javascript:void(0);">自定义</a></li>
	 *			</ul>
	 *		</div>
	 *		<input type="text" class="form-control" name="number" value="">
	 *		<input type="hidden" class="form-control" name="other" value="">
	 *	</div>
	 * demo2
	 *	<div class="input-group">
	 *		<div class="input-group-btn">
	 *			<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
	 *				<span class="placeholder">请选择</span>
	 *				<span class="fa fa-caret-down"></span>
	 *			</button>
	 *			<ul class="dropdown-menu" rel-action="target" rel-target="[name=other]">
	 *				<li><a href="javascript:void(0);" rel-data="require" rel-placeholder="已填写">必填</a></li>
	 *				<li><a href="javascript:void(0);" rel-data="read" rel-readonly="true">只读</a></li>
	 *				<li><a href="javascript:void(0);" rel-data="reset" rel-reset="true">重置</a></li>
	 *				<li><a href="javascript:void(0);" rel-data="data">普通</a></li>
	 *				<li><a href="javascript:void(0);" rel-data="last" rel-target="[name=number]" rel-reset="true">例外</a></li>
	 *				<li class="divider"></li>
	 *				<li><a href="javascript:void(0);">自定义</a></li>
	 *			</ul>
	 *		</div>
	 *		<input type="text" class="form-control" name="number" value="">
	 *		<input type="hidden" class="form-control" name="other" value="">
	 *	</div>
	 **/
	$("[rel-action=target]").each(function(){
		
		// 容器目标选择器
		var targets = $(this).attr('rel-target');
		var callback = $(this).attr('rel-callback') || '(function(){})';
		
		$(this).find('a').click(function(){
			// 事件目标选择器
			var target = $(this).attr('rel-target') || targets;
			// 事件值
			var data = $(this).attr('rel-data') || null;
			// 事件只读标识
			var readonly = $(this).attr('rel-readonly') || 'false';
			var disabled = $(this).attr('rel-disabled') || 'false';
			// 事件重置标识
			var reset = $(this).attr('rel-reset') || 'false';
			// 事件预期值提示信息
			var placeholder = $(this).attr('rel-placeholder') || $(this).html();//<span class="fa fa-caret-down"></span>
				
			// 事件操作
			$(target).val(data);
			$(target).parent().find('.placeholder').html(placeholder);
			
			$(targets).attr('readonly',readonly === 'false' ? false : true);
			$(targets).attr('disabled',disabled === 'false' ? false : true);
			
			// 重置操作
			if( reset === 'true' )
			{
				$(targets).val(null);
			}
			
			// 处理回调函数
			(function(callback,element,target,targets){
				return new callback(element,target,targets);
			})(eval(callback),$(this),$(target),$(targets));
		});
	});
	
	$("[rel-action=datepicker]").each(function(){
		var options = {};
		
		try{
			options = JSON.parse($(this).attr('rel-options') || '{}');
		}catch(e){
			console.error("JSON字符串为{\"key\":\"value\"}不支持{'key':'value'}及{key:'value'}");
			return true;
		}
		
		var config = $.extend({
			autoclose: true,
			format:'yyyy-mm-dd',
			todayBtn:true,
			todayHighlight:true,
			language:'zh-CN',
		},options);
		
		$(this).datepicker(config);
	});
	
	$("[rel-action=datetimepicker]").each(function(){
		var options = {};
		
		try{
			options = JSON.parse($(this).attr('rel-options') || '{}');
		}catch(e){
			console.error("JSON字符串为{\"key\":\"value\"}不支持{'key':'value'}及{key:'value'}");
			return true;
		}
		
		var config = $.extend({
			autoclose: true,
			format:'yyyy-mm-dd hh:ii:ss',
			todayBtn:true,
			todayHighlight:true,
			language:'zh-CN',
			minuteStep:1,
		},options);
		
		$(this).datetimepicker(config);
	});
	
	$("[rel-format=json]").each(function(){
		var auto = $(this).attr('rel-format-rows-auto') || true;
		var rows = $(this).attr('rows');
		
		try{
			var raw = JSON.parse($(this).val());
			var data = JSON.stringify(raw, undefined, '\t');
				$(this).val(data);
			var row = data.match(new RegExp("\n","g"));
				if( row == null ){
					return true;
				}
			var length = row.length + 1;
				if( auto === true && length > rows){
					$(this).attr('rows',length);
				}
		}catch(e){
			console.error(e);
		}
	});
	
	$("[rel-action=resize]").each(function(){
		var resize = $(this).prop('rel-resize') || 'none';
		
		$(this).css('resize',resize);
		
		try{
			var content = $(this).val();
			var rows = $(this).prop('rows');
			var row = content.match(new RegExp("\n","g"));
				if( row == null ){
					return true;
				}
			var length = row.length + 1;
				if( length > rows ){
					$(this).prop('rows',length);
				}
		}catch(e){
			console.error(e);
		}
	});
	
	$("[rel-action=viewer]").each(function(){
		$(this).viewer($(this).data());
	});
	
	$(document).on("click","[rel-action=dialog-close]",function(){
		parent.layer.close(parent.layer.getFrameIndex(window.name));
	});
	
	$(document).on("click","[rel-action=dialog-reload]",function(){
		window.self.location.href = window.self.location.href;
	});
	
	$(document).on("click","[rel-action=dialog-close-reload]",function(){
		//parent.layer.close(parent.layer.getFrameIndex(window.name));
		//window.parent.location.href = window.parent.location.href;
	});
	
	$(document).on("click","[rel-action=back]",function(){
		history.go(-1);
	});
	
	$("[rel-action=select]").each(function(){
		$(this).select2();
	});
	
	$("[rel-action=preview]").each(function(){
		$(this).previewThumb();
	});
	
});

function form_submit(obj){
    var url = $(obj).attr("action");
    var data = $(obj).serialize();
    var method = $(obj).attr("method");

    var callback = $(obj).attr("rel-callback");
    var success = $(obj).attr("rel-success") || 'document.location.href = data.url';
    var error = $(obj).attr("rel-error");
    $.ajax({
        url:url,
        data:data,
        type:method,
        //dataType:"json",
        beforeSend:function(XMLHttpRequest){},
        success:function(data,textStatus){
            if( data.url === '' )
            {
                data.url = window.location.href;
            }
            if( data.url == false )
            {
                success = false;
            }
            layer.msg(data.info,{
                shift: data.status ? 2 : 6
            });
            window.setTimeout(function(){
                if( data.status ){
                    eval(success);
                }
            },1000);
        },
        complete:function(XMLHttpRequest,textStatus){
            eval(callback);
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
            eval(error);
        }
    });

    return false;
}
function dialogClose()
{
	//parent.layer.close(parent.layer.getFrameIndex(window.name));
}
function dialogReload()
{
	//window.self.location.href = window.self.location.href;
}
function dialogCloseReload()
{
	//window.parent.location.href = window.parent.location.href;
}